package com.yuanqi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuanqi.pojo.AttachmentTypeConfig;
import com.yuanqi.service.AttachmentTypeConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 附件类型配置管理控制器
 */
@RestController
@RequestMapping("/api/sales/attachment-type")
public class AttachmentTypeConfigController {

    @Autowired
    private AttachmentTypeConfigService typeConfigService;

    /**
     * 分页查询附件类型配置
     * 方法名称：pageAttachmentTypeConfigs
     * 前端调用：GET /api/sales/attachment-type/page
     */
    @GetMapping("/page")
    public Map<String, Object> pageAttachmentTypeConfigs(
            @RequestParam(defaultValue = "1") Long pageNo,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String typeCode,
            @RequestParam(required = false) String typeName,
            @RequestParam(required = false) Integer status) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<AttachmentTypeConfig> page = new Page<>(pageNo, pageSize);
            IPage<AttachmentTypeConfig> result = typeConfigService.page(page);
            
            response.put("success", true);
            response.put("data", result);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 查询所有附件类型配置
     * 方法名称：getAllAttachmentTypeConfigs
     * 前端调用：GET /api/sales/attachment-type/list
     */
    @GetMapping("/list")
    public Map<String, Object> getAllAttachmentTypeConfigs() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<AttachmentTypeConfig> configs = typeConfigService.list();
            response.put("success", true);
            response.put("data", configs);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据状态查询附件类型配置
     * 方法名称：getAttachmentTypeConfigsByStatus
     * 前端调用：GET /api/sales/attachment-type/status/{status}
     */
    @GetMapping("/status/{status}")
    public Map<String, Object> getAttachmentTypeConfigsByStatus(@PathVariable Integer status) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<AttachmentTypeConfig> configs = typeConfigService.getByStatus(status);
            response.put("success", true);
            response.put("data", configs);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 根据类型编码查询附件类型配置
     * 方法名称：getAttachmentTypeConfigByCode
     * 前端调用：GET /api/sales/attachment-type/code/{typeCode}
     */
    @GetMapping("/code/{typeCode}")
    public Map<String, Object> getAttachmentTypeConfigByCode(@PathVariable String typeCode) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            AttachmentTypeConfig config = typeConfigService.getByTypeCode(typeCode);
            if (config != null) {
                response.put("success", true);
                response.put("data", config);
                response.put("message", "查询成功");
            } else {
                response.put("success", false);
                response.put("message", "配置不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 查询所有启用的附件类型配置（按排序顺序）
     * 方法名称：getEnabledAttachmentTypeConfigs
     * 前端调用：GET /api/sales/attachment-type/enabled
     */
    @GetMapping("/enabled")
    public Map<String, Object> getEnabledAttachmentTypeConfigs() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<AttachmentTypeConfig> configs = typeConfigService.getEnabledOrderBySort();
            response.put("success", true);
            response.put("data", configs);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 创建附件类型配置
     * 方法名称：createAttachmentTypeConfig
     * 前端调用：POST /api/sales/attachment-type
     */
    @PostMapping
    public Map<String, Object> createAttachmentTypeConfig(@RequestBody AttachmentTypeConfig config) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = typeConfigService.save(config);
            response.put("success", result);
            response.put("message", result ? "创建成功" : "创建失败");
            if (result) {
                response.put("data", config);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 更新附件类型配置
     * 方法名称：updateAttachmentTypeConfig
     * 前端调用：PUT /api/sales/attachment-type/{id}
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateAttachmentTypeConfig(
            @PathVariable Long id,
            @RequestBody AttachmentTypeConfig config) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            config.setId(id);
            boolean result = typeConfigService.updateById(config);
            response.put("success", result);
            response.put("message", result ? "更新成功" : "更新失败");
            if (result) {
                response.put("data", config);
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 删除附件类型配置
     * 方法名称：deleteAttachmentTypeConfig
     * 前端调用：DELETE /api/sales/attachment-type/{id}
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteAttachmentTypeConfig(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = typeConfigService.removeById(id);
            response.put("success", result);
            response.put("message", result ? "删除成功" : "删除失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 批量删除附件类型配置
     * 方法名称：deleteAttachmentTypeConfigs
     * 前端调用：DELETE /api/sales/attachment-type/batch
     */
    @DeleteMapping("/batch")
    public Map<String, Object> deleteAttachmentTypeConfigs(@RequestBody List<Long> ids) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean result = typeConfigService.removeByIds(ids);
            response.put("success", result);
            response.put("message", result ? "批量删除成功" : "批量删除失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 启用附件类型配置
     * 方法名称：enableAttachmentTypeConfig
     * 前端调用：PUT /api/sales/attachment-type/{id}/enable
     */
    @PutMapping("/{id}/enable")
    public Map<String, Object> enableAttachmentTypeConfig(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            AttachmentTypeConfig config = new AttachmentTypeConfig();
            config.setId(id);
            config.setStatus(1);
            boolean result = typeConfigService.updateById(config);
            response.put("success", result);
            response.put("message", result ? "启用成功" : "启用失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "启用失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 停用附件类型配置
     * 方法名称：disableAttachmentTypeConfig
     * 前端调用：PUT /api/sales/attachment-type/{id}/disable
     */
    @PutMapping("/{id}/disable")
    public Map<String, Object> disableAttachmentTypeConfig(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            AttachmentTypeConfig config = new AttachmentTypeConfig();
            config.setId(id);
            config.setStatus(0);
            boolean result = typeConfigService.updateById(config);
            response.put("success", result);
            response.put("message", result ? "停用成功" : "停用失败");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "停用失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 检查文件类型是否允许
     * 方法名称：checkFileTypeAllowed
     * 前端调用：GET /api/sales/attachment-type/check-file-type
     */
    @GetMapping("/check-file-type")
    public Map<String, Object> checkFileTypeAllowed(
            @RequestParam String fileName,
            @RequestParam String typeCode) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean allowed = typeConfigService.isFileTypeAllowed(fileName, typeCode);
            response.put("success", true);
            response.put("data", allowed);
            response.put("message", "检查成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 获取文件大小限制
     * 方法名称：getMaxFileSize
     * 前端调用：GET /api/sales/attachment-type/max-file-size/{typeCode}
     */
    @GetMapping("/max-file-size/{typeCode}")
    public Map<String, Object> getMaxFileSize(@PathVariable String typeCode) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            long maxSize = typeConfigService.getMaxFileSize(typeCode);
            response.put("success", true);
            response.put("data", maxSize);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }

    /**
     * 获取允许的文件扩展名列表
     * 方法名称：getAllowedExtensions
     * 前端调用：GET /api/sales/attachment-type/allowed-extensions/{typeCode}
     */
    @GetMapping("/allowed-extensions/{typeCode}")
    public Map<String, Object> getAllowedExtensions(@PathVariable String typeCode) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            List<String> extensions = typeConfigService.getAllowedExtensions(typeCode);
            response.put("success", true);
            response.put("data", extensions);
            response.put("message", "查询成功");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "查询失败：" + e.getMessage());
            e.printStackTrace();
        }
        
        return response;
    }
}
